# -*- coding: UTF-8 -*- #
"""
-------真正的勇士， 敢于直面惨淡的Warning、 敢于正视淋漓的Error-----
@author : 贾鹏博
@file : 9、结构化响应断言JSON.py
@time : 2022/5/14 22:44
"""

import json
import requests
from jsonpath import jsonpath


# =====================================   json 断言 (requests提供的) ===================================================
def test_hogwarts_json():
    url = 'https://home.testing-studio.com/categories.json'
    r = requests.get(url)
    print(r.text)
    assert r.status_code == 200
    assert r.json()['category_list']['categories'][3]['name'] == '测试开发'


# =================================   jsonpath 断言   安装 pip install jsonpath  ====================================
"""
   xpath                     jsonpath
/store/book/author          $.store.book[*].author
//author                     $..author
/store/*                     $.store.*
/store//price                $.store..price
//book[3]                    $..book[2]

"""


def test_hogwarts_jsonpath():
    url = 'https://home.testing-studio.com/categories.json'
    r = requests.get(url)
    # 打印所有 jsonpath 取出来的内容 ['开源项目', '测试开发', '职位内推', '测试服务', '社区治理', '未分类', '匿名讨论', '测试开发教材讨论区', '兴趣爱好交流', '霍格沃兹答疑区', '霍格沃兹测试开发学社', '面试专辑']
    print(jsonpath(r.json(), '$..name'))
    # =====================   第一个原始的数据，第二个为 jsonpath 表达式   $..表示深度遍历: 递归查找  ======================
    assert jsonpath(r.json(), '$..name')[3] == '测试开发'


# ==================================  xml  断言   安装 pip install requests_xml ===================================
from requests_xml import XMLSession

session = XMLSession()
r = session.get('https://www.nasa.gov/rss/dyn/lg_image_of_the_day.rss')
r.xml.links

# xml解析
import xml.etree.ElementTree as ET

# root = ET.fromstring(countrydata)
# root.findall(".")
# root.findall("./country/neighbor")
# root.findall(".//year/../[@name='Singapore']")
# root.findall(".//*[@name='Singapore']/year")
# root.findall(".//neighbor[2]")

# ===========================================   xpath 断言  =========================================
from requests_xml import XMLSession

session = XMLSession()
r = session.get('https://www.nasa.gov/rss/dyn/lg_image_of_the_day.rss')
r.xml.links
item = r.xml.xpath('//item', first=True)
print(item.text)

# =============================================   hamcrest断言体系  ====================================================
"""
框架自带 assert 体系 ： assert assertEqual
Hamcrest 体系 ： assertThat      ->  安装 ： pip install PyHamcrest
"""
from hamcrest import *


def test_hamcrest():
    url = 'https://home.testing-studio.com/categories.json'
    r = requests.get(url)



    assert r.status_code == 200
    # 正常的 assert 断言
    assert r.json()['category_list']['categories'][3]['name'] == '测试开发'
    # equal_to 匹配器    close_to 接近某个值
    assert_that(r.json()['category_list']['categories'][3]['name'], equal_to('测试开发'))


# =======================    schema 校验   ===================================================
# 适用场景 ： 针对接口几十个字段，代码又多又长，且断言不灵活 。 引用 schema ，先给 json 文件生成 schema 文件
# 安装 pip install jsonschema
"""
https://jsonschema.net/
生成 schema 文件
根据需要添加自定义规则
"""
from jsonschema import validate


def test_get_login_jsonschema():
    url = 'https://testerhome.com/api/v3/topics.json'
    data = requests.get(url, params={"limit": '2'}).json()
    schema = json.load(open('topic_schema.json'))
    validate(data, schema=schema)


"""
schema 自动检验
    每次运行时自动保存当前的 schema
    下次运行对比上次的 schema 如果发现变更就报错
    saveSchema + diffSchema
"""

# 研发失误 ： 把数据类型写错 ： 把 int 写成 str。导致客户端在解析数据时，解析失败，引发空指针异常(崩溃问题)
